import {
  computed, onMounted, reactive, ref,
} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  getDishCate, dishCategoryAdd, dishCategoryQueryOne, dishCategoryEdit,
} from '../../api/dishMgt';

export function useDishsData(image) {
  const categoryList = ref([]);
  const flavors = ref([]);
  const router = useRouter();
  const viewImage = ref(null);
  const dynamicValidateForm = reactive({
    domains: [],
  });
  async function getDishCateList() {
    const { data: { data } } = await getDishCate(1);
    categoryList.value = data.map((item) => ({ label: item.name, value: item.id }));
  }
  const params = computed(() => router.currentRoute.value.query);
  const formItems = ref([
    {
      label: '菜品名称',
      key: 'name',
      type: 'el-input',
      width: 400,
      placeholder: '请填写菜品名称',
      rules: [
        { required: true, message: '请填写菜品名称', trigger: 'blur' },
      ],
    },
    {
      label: '菜品分类',
      key: 'categoryId',
      type: 'el-select',
      width: 400,
      options: categoryList,
      placeholder: '请选择菜品分类',
      rules: [
        { required: true, message: '请选择菜品分类', trigger: 'blur' },
      ],
    },
    {
      label: '菜品价格',
      key: 'price',
      type: 'el-input',
      width: 400,
      placeholder: '请选择菜品价格',
      rules: [
        { required: true, message: '请选择菜品价格', trigger: 'blur' },
      ],
    },
    {
      label: '口味做法配置',
      key: 'config',
      isSlot: true,
    },
    {
      label: '菜品图片',
      key: 'image',
      isSlot: true,
    },
    {
      label: '菜品描述',
      key: 'description',
      type: 'el-input',
      inputType: 'textarea',
      width: 800,
      rows: 5,
      placeholder: '菜品描述，最长200字',
    },
  ]);
  const formProps = reactive({
    model: {},
    formItems,
  });
  async function saveData() {
    if (!image.value) {
      ElMessage.error('请上传菜品图片!');
      return false;
    }
    flavors.value = dynamicValidateForm.domains.map((item) => ({ name: item.value, value: JSON.stringify(item.tags), showOption: false }));
    const dataParams = {
      ...formProps.model,
      image: image.value.value || null,
      dishFlavors: flavors.value,
    };
    try {
      params.value.page !== 'add' ? await dishCategoryEdit(dataParams) : await dishCategoryAdd(dataParams);
      router.go(-1);
    } catch (e) {
      await Promise.reject(e);
    }
  }
  async function dishQueryOne() {
    const { data: { data } } = await dishCategoryQueryOne(params.value.id);
    viewImage.value = data.image;
    for (const key in data) {
      formProps.model[key] = data[key];
    }
    dynamicValidateForm.domains = data.dishFlavors.map((item) => ({ value: item.name, tags: JSON.parse(item.value) }));
  }
  onMounted(() => {
    if (params.value.page === 'edit') {
      dishQueryOne().then((r) => {});
    }
    getDishCateList().then((r) => {});
  });
  return {
    formProps,
    saveData,
    viewImage,
    dynamicValidateForm,
  };
}
